package org.springframework.prospring.ticket.web;

import org.springframework.validation.Errors;
import org.springframework.validation.BindException;
import org.springframework.prospring.ticket.service.ReservationFieldRequest;
import org.springframework.prospring.ticket.service.UserManager;
import org.springframework.prospring.ticket.web.form.LoginForm;
import org.springframework.prospring.ticket.common.KeyConstant;
import org.springframework.prospring.ticket.domain.user.User;
import org.springframework.web.util.WebUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.HashMap;

/**
 * Form controller issuing a ReservationRequest on behalf of the user.
 * The user has selected a show, a price band and a date in the previous
 * screen(s) and this form controller will create the reservation
 * request based on this. Together with the amount of seats the user will
 * be selected, this form controller completes the request.<p>
 *
 * Input:
 * <ul>
 *   <li><code>performanceId</code>: the performance identifier</li>
 *   <li><code>priceBandId</code>: the price band identifier</li>
 * </ul>
 * Error conditions:
 * <ul>
 *  <li>When not enough seats are available anymore</li>
 * </ul>
 */
public class LoginController extends SimpleFormController {

    // the next view name, or controler forward.
    private String viewForward;

    UserManager userManager;
    /*
	 * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
	 */
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("ReserveFieldController.formBackingObject");
        }
        LoginForm loginForm = new LoginForm();
        loginForm.setViewNameToReturn(request.getParameter(KeyConstant.VIEW_NAME_TO_RETURN_KEY));

        return loginForm;
    }

    /**
     * Binds the maximum number of seats the user will be able to select
     * (key = <code>maximumSeats</code>) and hte default selected value
     * (<code>defaultSelected</code>).
     */
/*    protected Map referenceData(HttpServletRequest request, Object o, Errors errors) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("ReserveFieldController.referenceData");
        }
        LoginForm loginForm = (LoginForm)o;

        //request.getSession().getServletContext()
        //alexis tenes  poner la lista de los deportes en el contexto de la app
        //WebUtils.setSessionAttribute(request, "loginForm", loginForm );

        Map m = new HashMap();

        //m.put("loginForm", loginForm);

        return m;
    }*/

    /*
    protected void onBind(HttpServletRequest request, Object command,
                          BindException errors) {

        LoginForm loginForm = (LoginForm)command;

        errors.rejectValue("nickname", "error.trade.invalid-symbol", new Object[] { "asdfasd" },
                    "Invalid ticker symbol.");

    }
    */

    /*
    protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors)
            throws Exception {

        errors.setNestedPath("");

        errors.reject("PASSWORD_MISMATCH", "Passwords did not match. Matching passwords are required.");
    }
    */
    /**
     * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(
     *      javax.servlet.http.HttpServletRequest,
            javax.servlet.http.HttpServletResponse,
            Object,
            org.springframework.validation.BindException)
     */
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,
                                    Object o, BindException errors) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("ReserveFieldController.onSubmit");
        }


        // the object is an already filled in reservation reservationFieldRequest
        LoginForm loginForm = (LoginForm)o;

        System.out.println("alexis emmanuel quiros");
        User user = userManager.checkUser(loginForm.getNickname(), loginForm.getPassword());

        /*
        // putting the reservation and performance in session, for future reference.
        WebUtils.setSessionAttribute(httpRequest, "reservationFieldRequest", reservationFieldRequest);

        // redirecting the another controller that will show the reservation.
        // this is done to prevent the user from resubmitting the form.
        reservationFieldRequest.setSuccessView(getSuccessView());
        */

        ModelAndView mav = null;
        if (user != null) {
            UserContext userContext = new UserContext();
            userContext.setId(user.getId());
            userContext.setNickname(user.getNickname());
            userContext.setFirstName(user.getFirstName());
            WebUtils.setSessionAttribute(request, KeyConstant.USER_CONTEXT_KEY, userContext);

            String successView;
            if (StringUtils.isNotEmpty(loginForm.getViewNameToReturn()))
                successView = loginForm.getViewNameToReturn();
            else
                successView =  getSuccessView();
            mav = new ModelAndView(new RedirectView(successView));
        } else {
            errors.reject("error.user.login.invalid", "Sorry, we could not find the combination you entered. Please try again");
            return showForm(request, response, errors, errors.getModel());
            //return showForm(httpRequest, errors, getFormView());
/*
            String formAttrName = getFormSessionAttributeName(httpRequest);
            mav = new ModelAndView(getFormView());
            mav.addObject(formAttrName, errors);
            mav.addObject(getCommandName(), errors);
*/
        }

        if (logger.isDebugEnabled()) {
            logger.debug("ModelAndView: "+mav.toString());
        }

        return mav;
    }


    public String getViewForward() {
        return viewForward;
    }

    public void setViewForward(String viewForward) {
        this.viewForward = viewForward;
    }

    public UserManager getUserManager() {
        return userManager;
    }

    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    //====================================== Helper Method (some used for testing) ====================================

    /**
     * Creates a new ReservationRequest with the given values. This method can be used
     * in test cases to overriden and by that mock the created reservation request.
     * @param regions The regions that could be selecte to do a field's reservation.
     * @return A new reservation field request.
     */
/*    protected ReservationFieldRequest createReservationFieldRequest(Collection<Region> regions) {
        if (logger.isDebugEnabled()) {
            logger.debug("ReserveFieldController.createReservationFieldRequest");
        }

        ReservationFieldRequest reservationFieldRequest = new ReservationFieldRequest();

        reservationFieldRequest.setSuccessView(getSuccessView());
        reservationFieldRequest.setRegions(regions);

        return reservationFieldRequest;
    }*/

}
